package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.SetmealMapper;
import com.itheima.domian.Setmeal;
import com.itheima.domian.SetmealDish;
import com.itheima.dto.SetmealDto;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired//套餐菜品
    SetmealDishService setmealDishService;

    @Override
    public void add(SetmealDto setmealDto) {
        //将套餐添加给 套餐
        this.save(setmealDto);
        //添加套餐菜品
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);

    }

    //起售
    @Override
    public void updateStatus(Long[] ids) {
        //根据id修改对应的数据  将状态修改为1
        //创建对象 设置属性
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(1);
        this.update(setmeal, Wrappers.<Setmeal>lambdaQuery().in(Setmeal::getId, Arrays.asList(ids)));
    }

    //停售
    @Override
    public void updateStop(Long[] ids) {
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(0);
        this.update(setmeal, Wrappers.<Setmeal>lambdaQuery().in(Setmeal::getId, Arrays.asList(ids)));

    }

    //删除
    @Override
    public void delete(Long[] ids) {
        this.remove(Wrappers.<Setmeal>lambdaQuery().in(Setmeal::getId, Arrays.asList(ids)));
    }

    //修改数据回显
    @Override
    public SetmealDto querySetmealById(Long id) {
        //根据id查询套餐
        Setmeal setmeal = this.getById(id);
        //根据套餐id查询 菜品
        List<SetmealDish> list = setmealDishService.list(Wrappers.lambdaQuery(SetmealDish.class).eq(SetmealDish::getSetmealId, id));
        SetmealDto setmealDto = new SetmealDto();
        BeanUtils.copyProperties(setmeal, setmealDto);
        setmealDto.setSetmealDishes(list);

        return setmealDto;
    }

    //修改数据
    @Override
    public void updateSetmeal(SetmealDto setmealDto) {
        //修改 套餐表
        this.updateById(setmealDto);
        //修改口味表  因为不知道修改了什么 所以需要 将口味表的信息全部删  再添加

        setmealDishService.remove(Wrappers.lambdaQuery(SetmealDish.class).eq(SetmealDish::getSetmealId, setmealDto.getId()));
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> setmealDish.setSetmealId(setmealDto.getId()));
        setmealDishService.saveBatch(setmealDishes);
    }
}
